<template>
  <div>
    <div class="card mb-3 r-form">
      <div class="card-body" v-if="viewMode === 2">
        <div class="font-weight-bold mb-3">展期信息：</div>
        <div class="d-flex mb-2">
          <label class="col-form-label r-form-label">展期还款时间</label>
          <div class="flex-1 mb-2">
            <el-date-picker
              v-model="formData.new_load_end_date"
              class="w-100"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择"
              :picker-options="pickerOptions"
              :default-value="defaultDate"
            ></el-date-picker>
          </div>
          <label class="col-form-label r-form-label">展期附件</label>
          <div class="flex-1">
            <upload-oss
              multiple
              listType="picture-card"
              ref="uploadFinish"
              accept="image/*"
              :on-complete="handleCompleteFinish"
              :file-list="finishFileList"
              class="form-control-ml"
            ></upload-oss>
          </div>
        </div>
      </div>
      <div class="card-body" v-else>
        <div class="font-weight-bold mb-3">展期{{ isEdit ? '申请' : '信息' }}：</div>
        <div class="d-flex mb-2">
          <label class="col-form-label r-form-label">{{ isEdit ? '预计' : '' }}展期时间</label>
          <div class="flex-1 mb-2">
            <el-date-picker
              v-model="formData.new_load_end_date"
              class="w-100"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择"
              :picker-options="pickerOptions"
              :default-value="defaultDate"
              :disabled="!editEnable"
            ></el-date-picker>
          </div>
          <label class="col-form-label r-form-label">情况说明</label>
          <div class="flex-1">
            <el-input type="textarea" v-model="formData.des" :disabled="!editEnable"></el-input>
          </div>
        </div>
        <div class="d-flex mb-2">
          <label class="col-form-label r-form-label">附件上传</label>
          <div class="flex-1">
            <img-card :images="attachList" v-if="!editEnable"></img-card>
            <upload-oss
              v-else
              multiple
              listType="picture-card"
              ref="upload"
              accept="image/*"
              :on-complete="handleComplete"
              :file-list="fileList"
              class="form-control-ml"
            ></upload-oss>
          </div>
        </div>
      </div>
    </div>

    <div class="mb-3 text-center" v-if="viewMode === 1">
      <el-button type="primary" class="btn-long" :loading="loading" @click="agreePostpone">
        同意展期
      </el-button>
      <el-button class="btn-long" :disabled="loading" @click="rejectPostpone">拒绝</el-button>
    </div>

    <div class="mb-3 text-center" v-if="viewMode === 2">
      <el-button type="primary" class="btn-long" :loading="loading" @click="agreeFinish">
        完成
      </el-button>
      <el-button class="btn-long" :disabled="loading" @click="rejectFinish">拒绝</el-button>
    </div>

    <div class="mb-3 text-center" v-else-if="viewMode === 0">
      <el-button type="primary" class="btn-long" :loading="loading" @click="submit">完成</el-button>
      <el-button class="btn-long" :disabled="loading" @click="dismiss">取消</el-button>
    </div>

    <div class="card mb-3" v-if="viewMode === 3 && +renewalData.approval_status === 3">
      <div class="card-body">
        <div class="font-weight-bold mb-3">拒绝信息：</div>
        <div class="d-flex mb-2">
          <div class="flex-1">
            <div class="d-flex mb-2">
              <label class="col-form-label r-form-label">拒绝时间</label>
              <div class="flex-1 input-static">{{ renewalData.confuse_time }}</div>
            </div>
            <div class="d-flex">
              <label class="col-form-label r-form-label">操作人</label>
              <div class="flex-1 input-static">{{ renewalData.confuse_person }}</div>
            </div>
          </div>
          <div class="flex-1 d-flex">
            <label class="col-form-label r-form-label">拒绝理由</label>
            <div class="flex-1 input-static">{{ renewalData.confuse_reason }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { dateFromString, arrayFromString } from '@vimi/utils-tool'
import { strFromOss } from '@/common/plugins/tools/format'

import ImgCard from '@/components/ImgCard'

export default {
  components: {
    ImgCard,
  },
  props: {
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    renewalData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      loading: false,
      tableName: 'credit_extended_loan',
      formData: {
        new_load_end_date: '',
        des: '',
        attachment: '',
      },
      attachList: [],
      fileList: [],
      finishFileList: [],
    }
  },
  computed: {
    ...mapGetters(['user']),
    loadEndDate() {
      return dateFromString(this.relatedData.load_end_date) || Date.now()
    },
    pickerOptions() {
      return {
        disabledDate: time => time <= this.loadEndDate,
        shortcuts: [
          {
            text: '展期一个月',
            onClick: picker => {
              const date = new Date(+this.loadEndDate + 8.64e7 * 30)
              picker.$emit('pick', date)
            },
          },
          {
            text: '展期半年',
            onClick: picker => {
              const date = new Date(+this.loadEndDate + 8.64e7 * 182)
              picker.$emit('pick', date)
            },
          },
          {
            text: '展期一年',
            onClick: picker => {
              const date = new Date(+this.loadEndDate + 8.64e7 * 365)
              picker.$emit('pick', date)
            },
          },
        ],
      }
    },
    defaultDate() {
      return this.loadEndDate
    },
    isAddEdit() {
      return !this.renewalData.credit_extended_loan_id
    },
    isEdit() {
      return this.viewMode === 0
    },
    isApproval() {
      return this.viewMode === 1
    },
    editEnable() {
      return this.isEdit || this.isApproval
    },
  },
  watch: {
    relatedData: {
      handler: function (val) {
        this.initRelatedData(val)
      },
      deep: true,
      immediate: true,
    },
    renewalData: {
      handler: function (val) {
        this.init(val)
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    init(val) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = val[key] || ''
      })
      this.attachList = arrayFromString(val.attachment)
      this.fileList = this.attachList.map(item => ({ url: item }))
    },
    initRelatedData() {
      this.formData.new_load_end_date = this.renewalData.new_load_end_date || ''
    },
    dismiss() {
      this.$emit('dissmiss', true)
    },
    submit() {
      this.validate()
        .then(() => {
          this.$refs.upload.submit()
        })
        .catch(err => {
          this.$message.error((err && err.message) || '输入错误，请重新输入')
        })
    },
    validate() {
      return new Promise((resolve, reject) => {
        if (this.isAddEdit && (!this.relatedData || !this.relatedData.customer_related_id)) {
          reject(new Error('请选择贷后项目'))
        } else if (!this.formData.new_load_end_date) {
          reject(new Error('请选择预计展期时间'))
        } else if (!this.formData.des) {
          reject(new Error('请填写情况说明'))
        } else {
          resolve()
        }
      })
    },
    handleComplete(images) {
      this.formData.attachment = strFromOss(images)
      if (this.viewMode === 1) {
        this.updatePostpone()
      } else {
        const id = this.renewalData.credit_extended_loan_id
        if (id) {
          this.updateData(id, this.formData, '修改')
        } else {
          const data = {
            ...this.formData,
            ...this.copyFromRelated(),
            extended_loan_type: 1,
          }
          this.addData(data)
        }
      }
    },
    copyFromRelated() {
      const { relatedData } = this
      return [
        'address',
        'address_code',
        'customer_name',
        'customer_related_id',
        'left_funds',
        'load_end_date',
        'mobile_no',
        'res_person',
        'corp_name',
        'service_id',
        'res_a',
        'res_b',
      ].reduce((prev, key) => {
        prev[key] = relatedData[key]
        return prev
      }, {})
    },
    async addData(data) {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.addData(this.$serviceName, this.tableName, data)
      )
      this.loading = false
      if (!res) return this.$message.error('登记失败，请重试')
      this.$message.success('登记成功')
      this.$emit('success', res)
    },
    async updateData(id, data, label) {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData(this.$serviceName, this.tableName, id, data)
      )
      this.loading = false
      if (!res) return this.$message.error(`${label}失败，请重试`)
      this.$message.success(`${label}成功`)
      this.$emit('success', res)
    },
    agreePostpone() {
      this.$utils.msgbox({
        message: '确定同意展期?',
        beforeClose: () => this.$refs.upload.submit(),
      })
    },
    rejectPostpone() {
      this.$prompt('拒绝理由：', '展期拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入拒绝理由',
        inputType: 'textarea',
        inputValidator: value => (!value ? '请输入拒绝理由' : true),
      }).then(({ value }) => {
        this.updateData(
          this.renewalData.credit_extended_loan_id,
          {
            confuse_person: this.user.realName,
            confuse_time: this.$utils.dateFormat(new Date()),
            confuse_reason: value,
            approval_status: 3,
          },
          '拒绝'
        )
      })
    },
    updatePostpone() {
      this.updateData(
        this.renewalData.credit_extended_loan_id,
        {
          ...this.formData,
          approval_status: 1,
        },
        '同意展期'
      )
    },
    agreeFinish() {
      if (!this.formData.new_load_end_date) {
        return this.$message.error('请选择展期还款时间')
      }
      this.$refs.uploadFinish.submit()
    },
    handleCompleteFinish(images) {
      const attachment = strFromOss([...this.fileList, ...images])
      const id = this.renewalData.credit_extended_loan_id
      this.updateData(
        id,
        {
          new_load_end_date: this.formData.new_load_end_date,
          attachment,
          approval_status: 2,
          extended_loan_type: 1,
        },
        '完成展期'
      )
    },
    rejectFinish() {
      this.$prompt('拒绝理由：', '展期拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入拒绝理由',
        inputType: 'textarea',
        inputValidator: value => (!value ? '请输入拒绝理由' : true),
      }).then(({ value }) => {
        this.updateData(
          this.renewalData.credit_extended_loan_id,
          {
            confuse_person: this.user.realName,
            confuse_time: this.$utils.dateFormat(new Date()),
            confuse_reason: value,
            approval_status: 3,
          },
          '拒绝'
        )
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.r-form {
  /deep/ .el-input.is-disabled .el-input__inner,
  /deep/ .el-textarea.is-disabled .el-textarea__inner {
    color: $gray-600;
  }
  &-label {
    width: 110px;
    text-align: right;
    margin-right: 0.5rem;
  }
}
.input-static {
  border-radius: 4px;
  border: 1px solid $border-color;
  padding: 6px 15px;
  min-height: 36px;
  background-color: #f5f7fa;
  color: $gray-600;
  cursor: not-allowed;
}
</style>
